package com.faintlight.controller;

import com.faintlight.dto.CapsuleDTO;
import com.faintlight.model.Capsule;
import com.faintlight.service.CapsuleService;
import com.faintlight.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/capsules")
@Tag(name = "时光胶囊", description = "时光胶囊管理接口")
@RequiredArgsConstructor
public class CapsuleController {

    private static final Logger logger = LoggerFactory.getLogger(CapsuleController.class);

    private final CapsuleService capsuleService;
    private final UserService userService;

    @PostMapping
    @Operation(summary = "创建新时光胶囊")
    public ResponseEntity<Capsule> createCapsule(@Valid @RequestBody Capsule capsule, @RequestHeader("X-User-Id") Long userId) {
        capsule.setCreatedBy(userService.getUserById(userId));
        Capsule saved = capsuleService.createCapsule(capsule);
        logger.info("✅ 时光胶囊创建成功, ID={}", saved.getId());
        return ResponseEntity.ok(saved);
    }

    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户所有时光胶囊")
    public ResponseEntity<List<CapsuleDTO>> getUserCapsules(@PathVariable Long userId) {
        logger.info("🔍 查询用户 {} 的所有时光胶囊", userId);
        List<CapsuleDTO> capsules = capsuleService.getUserCapsulesAllStatus(userId);
        return ResponseEntity.ok(capsules);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取胶囊详情")
    public ResponseEntity<CapsuleDTO> getCapsuleDetail(@PathVariable Long id) {
        Capsule capsule = capsuleService.getCapsuleById(id);
        if (capsule == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(CapsuleDTO.fromEntity(capsule));
    }

    @PostMapping("/{id}/unlock")
    @Operation(summary = "手动解锁时光胶囊（测试用）")
    public ResponseEntity<Capsule> unlockCapsule(@PathVariable Long id) {
        Capsule unlocked = capsuleService.unlockCapsule(id);
        return ResponseEntity.ok(unlocked);
    }
    // CapsuleController.java
    @GetMapping("/user/{userId}/count")
    @Operation(summary = "获取用户时光胶囊数量")
    public ResponseEntity<Long> getUserCapsuleCount(@PathVariable Long userId) {
        Long count = capsuleService.getUserCapsuleCount(userId);
        return ResponseEntity.ok(count);
    }
}
